package com.dinetech.ejecutor;

import java.util.ArrayList;

import com.dinetech.dao.SpinnerVariosAdapter;
import com.dinetech.dao.UbicacionAdapter;
import com.dinetech.dao.WSEvento;
import com.dinetech.entidades.Personal;
import com.dinetech.entidades.Session;
import com.dinetech.entidades.Ubicacion;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class EventoRecria extends Fragment implements OnClickListener{

	private static final String ID_GALPON="0";
	Spinner cbxUbicR, cbxGeneroR, cbxRespR, cbxLGR;
	EditText txtCant, txtObs;
	Button btnGrabarR;
	Personal perR = Personal.getInstance();
	int idUsuario, idUbicacion, idGalpon;
	String idGenero, idLineaGenetica;
	Session ses= Session.getInstance();
	
	public static EventoRecria newInstance (int IdGalpon){
		
		EventoRecria eventoR = new EventoRecria();
		
		Bundle bundle = new Bundle();
		bundle.putInt(ID_GALPON, IdGalpon);
		eventoR.setArguments(bundle);
		eventoR.setRetainInstance(true);
		
		return eventoR;
	}
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		ViewGroup view = (ViewGroup)inflater.inflate(R.layout.evento_recria,container, false);
		
		cbxUbicR = (Spinner)view.findViewById(R.id.cbxPozaR);
		cbxGeneroR = (Spinner)view.findViewById(R.id.cbxSexoR);
		cbxLGR = (Spinner)view.findViewById(R.id.cbxLineaGeneticaR);
		cbxRespR = (Spinner)view.findViewById(R.id.cbxResponsableR);
		txtCant = (EditText)view.findViewById(R.id.txtCantR);
		txtObs = (EditText)view.findViewById(R.id.txtComentarioR);
		btnGrabarR = (Button)view.findViewById(R.id.btnRecria);
		btnGrabarR.setOnClickListener(this);
		this.idGalpon = getArguments().getInt(ID_GALPON);
		new listarUbicacion().execute();
		llenarSpinner();
		
		return view;
	}

	private void refrescarRecria(){
		new listarUbicacion().execute();
		llenarSpinner();
		txtObs.setText("");
		txtCant.setText("");
	}
	
	private void llenarSpinner(){

		SpinnerVariosAdapter adaptadorG = new SpinnerVariosAdapter(EventoRecria.this, ses.getLISTA_GENERO());
		cbxGeneroR.setAdapter(adaptadorG);
		cbxGeneroR.setOnItemSelectedListener(new SpinnerListenerGenero());
		
		
		SpinnerVariosAdapter adaptadorLG = new SpinnerVariosAdapter(EventoRecria.this, ses.getLISTA_LINEA_GENETICA());
		cbxLGR.setAdapter(adaptadorLG);
		cbxLGR.setOnItemSelectedListener(new SpinnerListenerLG());
		
		SpinnerVariosAdapter adaptadorRes = new SpinnerVariosAdapter(EventoRecria.this, ses.getLISTA_RESPONSABLE());
		cbxRespR.setAdapter(adaptadorRes);
		cbxRespR.setOnItemSelectedListener(new SpinnerListenerResp());
		
		for(int i=0; i <  adaptadorRes.getCount(); i++){
			int idRA=(int)(long)adaptadorRes.getItemId(i) ;
			idUsuario = perR.getIdPersonal();
			if( idRA == idUsuario){
				cbxRespR.setSelection(i);					
			}	        
		}
		
	}
	
	public class SpinnerListenerUbic implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUbicacion= convert;	
            
            if(idUbicacion==0){
				btnGrabarR.setEnabled(false);
			}
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
		
	public class SpinnerListenerGenero implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));

            if(convert < 10)
            {
            	idGenero ="0" + String.valueOf(convert);
            }
            else
            {
            	idGenero = String.valueOf(convert);
            }
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	public class SpinnerListenerLG implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            	
            if(convert < 10)
            {
            	idLineaGenetica ="0" + String.valueOf(convert);
            }
            else
            {
            	idLineaGenetica = String.valueOf(convert);
            }
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	public class SpinnerListenerResp implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUsuario= convert;	            	         
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	private class listarUbicacion extends AsyncTask<String, Void, ArrayList<Ubicacion>>{

		@Override
		protected ArrayList<Ubicacion> doInBackground(String... params) {
			ArrayList<Ubicacion> listaUbicacion;
			WSEvento wsE = new WSEvento();
			
			listaUbicacion = wsE.ubicacionPorEvento("06", idGalpon, 1, 1, 1, 0, perR.getIdSucursal());
			
			return listaUbicacion;
		}

		@Override
		protected void onPostExecute(ArrayList<Ubicacion> result) {
			super.onPostExecute(result);
			
			UbicacionAdapter adaptadorUbic = new UbicacionAdapter(EventoRecria.this, result);
			cbxUbicR.setAdapter(adaptadorUbic);
			cbxUbicR.setOnItemSelectedListener(new SpinnerListenerUbic());
			
			
			
		}
		
	}
	
	private class grabarR extends AsyncTask<String, Void, String>{
		
		
		@Override
	    protected String doInBackground(String... urls) {

	    	WSEvento we= new WSEvento();
	    	String Msg="";
	    	if(idGenero.equals("01")){
	    		Msg = we.grabarEvento("01", "06", "0", idLineaGenetica, ses.obtenerFechaActual(), String.valueOf(idUbicacion), "0", 
	    				Integer.parseInt(txtCant.getText().toString()), 0, 0, "0", "0", "0", idGenero, 0, txtObs.getText().toString(), 
	    				idUsuario, ses.obtenerFechaActual2(), perR.getIdPersonal(), 0, "0", perR.getIdSucursal(), idGalpon,0,0);
	    	}
	    	else if(idGenero.equals("02")){
	    		Msg = we.grabarEvento("01", "06", "0", idLineaGenetica, ses.obtenerFechaActual(), String.valueOf(idUbicacion), "0", 
	    				0, Integer.parseInt(txtCant.getText().toString()), 0, "0", "0", "0", idGenero, 0, txtObs.getText().toString(), 
	    				idUsuario, ses.obtenerFechaActual2(), perR.getIdPersonal(), 0, "0", perR.getIdSucursal(), idGalpon,0,0);
	    	}
	    		
	    	 return Msg;
	        	
	    }

	    @Override
	    protected void onPostExecute(String resultadoWS) {
	        super.onPostExecute(resultadoWS);	
	         
	        Toast msg = Toast.makeText(getActivity(), resultadoWS, Toast.LENGTH_LONG);
	        msg.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	        msg.show();
	        refrescarRecria();
	        
	    }
	}

	@Override
	public void onClick(View v) {
		
		if(txtCant.getText().length()==0){
			txtCant.setText("0");
		}
		
		int cantHembras= Integer.parseInt(txtCant.getText().toString());
		
		if(cantHembras < 1){
			AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());
			
			alerta.setTitle("Alerta");			
			alerta.setMessage("La cantidad de animales no puede ser menor a 1");			
			alerta.setPositiveButton("OK", 
					new DialogInterface.OnClickListener() {
			     public void onClick(DialogInterface dialog, int which) {
			     }
			    });
			alerta.show();			
			
		}else{
			new grabarR().execute();
		}
		txtCant.requestFocus();
	}

	
}
